import dayjs from 'dayjs'
class Utils {
	baseUrl = "http://159.75.169.224:7300/pz"
	http(options) {
		console.log(options);
		if (!options.url) return false;
		if (options.showLoading) {
			this.showLoading()
		}
		return new Promise((resolve, reject) => {
			uni.request({
				url: this.baseUrl + options.url,
				data: options.data || {},
				header: options.header || {},
				method: options.method || "GET",
				success(res) {
					uni.hideLoading()
					if (res.data.code !== 10000) {
						if (options.fail && typeof options.fail == "function") {
							options.fail(res.data)
						}
						reject(res.data)
						setTimeout(() => {
							uni.showToast({
								title: res.data.msg,
								icon: 'error'
							})
						}, 2000)
					} else {
						console.log('http', res.data);
						if (options.success && typeof options.success == "function") {
							options.success(res.data)
						}
						resolve(res.data)
					}
				},
				fail(res) {
					uni.hideLoading()
					reject(res.data)
					if (options.fail && typeof options.fail == "function") {
						options.fail(res.data)
					}
				}
			})
		})
	}
	getUserInfo() {
		return new Promise((resolve, reject) => {
			uni.login({
				success: (res) => {
					this.http({
						url: '/auth/wxLogin',
						data: {
							code: res.code
						},
						success: (res) => {
							uni.setStorageSync('userInfo', JSON.stringify(res
								.data.userinfo) || {})
							resolve(res.data.userinfo)
						},
						fail: (res) => {
							console.log(res, '60606060')
							reject(res)
						},
						showLoading: true
					})
				},
				fail(err) {
					console.log("fail", err);
				}
			})
		})
	}

	showLoading() {
		const isHasLoading = uni.getStorageSync('loading')
		if (isHasLoading) {
			uni.hideLoading()
			uni.setStorageSync("loading", false)
		}
		uni.showLoading({
			title: "加载中...",
			complete() {
				uni.setStorageSync("loading", true)
			},
			fail() {
				uni.setStorageSync("loading", false)
			}
		})
	}
	formatTime(date, pattern) {
		return dayjs(date).format(pattern)
	}
	//腾讯转百度：
	changeToBd(lat, lng) {
		var x_pi = (3.14159265358979324 * 3000.0) / 180.0;
		var x = parseFloat(lng);
		var y = parseFloat(lat);
		var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
		var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
		lng = z * Math.cos(theta) + 0.0065;
		lat = z * Math.sin(theta) + 0.006;
		return {
			lng,
			lat
		};
	}
	//百度转腾讯：
	changeToTx(lat, lng) {
		if (!lng || !lat) return {
			lng: 0,
			lat: 0
		};
		var x_pi = (3.14159265358979324 * 3000.0) / 180.0;
		var x = lng - 0.0065;
		var y = lat - 0.006;
		var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
		var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
		var lng = z * Math.cos(theta);
		var lat = z * Math.sin(theta);
		return {
			lng,
			lat
		};
	}
}

export default new Utils()